<template>
    <div class="production-plan">
      <el-button type="primary" @click="saveAll">保存主表单和明细</el-button>
      
      <h3 class="title">新增到货检验</h3>
  
      <!-- 基本信息 -->
      <el-form ref="formRef" :model="formData" :rules="rules" label-position="right" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="检验主题">
              <el-input v-model="formData.inspectionSubject" placeholder="请输入主题" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="检验单号">
              <el-input v-model="formData.inspectionOrderNumber" placeholder="请输入编号" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="7">
          <el-form-item label="检验日期" prop="inspectionDate" class="bordered-form-item">
            <el-date-picker
              v-model="formData.inspectionDate"
              type="date"
              required
              
            ></el-date-picker>
          </el-form-item>
        </el-col>
          <el-col :span="6">
            <el-form-item label="检验人员" prop="inspectionPersonnel" required>
              <el-input v-model="formData.inspectionPersonnel" placeholder="系统自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
          <el-form-item label="所在部门">
                  <el-select v-model="formData.department" placeholder="请选择检测方法">
                  <el-option label="生产部门" value="生产部门" />
                  <el-option label="采购部门" value="采购部门" />
                  <el-option label="物料部门" value="物料部门" />
                  <el-option label="包装部门" value="包装部门" />
                  <el-option label="质检部门" value="质检部门" />
                  </el-select>
              </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系电话" prop="contactInformation">
              <el-input v-model="formData.contactInformation" placeholder="请输入11位手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备注">
              <el-input v-model="formData.remarks" placeholder="请输入备注"  type="textarea"/>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 父件信息 -->
        <h2>采购信息</h2>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="采购单号">
              <el-input placeholder="请输入" v-model="formData.purchaseOrderNumber" required>
                <template #suffix>
                  <el-button size="mini" @click="openAssociatedItemDialog1">
                    <i class="el-icon-search"></i>
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
          <el-form-item label="采购日期" prop="purchaseDate" class="bordered-form-item">
            <el-date-picker
              v-model="formData.purchaseDate"
              type="date"
              required
              
            ></el-date-picker>
          </el-form-item>
        </el-col>
          <el-col :span="6">
            <el-form-item label="供应商名称">
              <el-input v-model="formData.supplierName" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系人">
              <el-input v-model="formData.contactPerson" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="formData.contactPhone" placeholder="请输入11位手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="采购人员">
              <el-input v-model="formData.purchasingPersonnel" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="采购部门">
              <el-input v-model="formData.purchasingDepartment" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系电话" prop="contactMethod">
              <el-input v-model="formData.contactMethod" placeholder="请输入11位手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="关联项目">
              <el-input v-model="formData.relatedProject" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 明细 -->
      <div class="detail-section">
        <h4 class="sub-title">检验明细表</h4>
        <el-button size="small" @click="addNewRow">新增行</el-button>
        <el-table :data="planDetailsList" border style="width: 100%">
          <el-table-column label="物品编号" width="180px">
            <template #default="{ row }">
              <el-input v-model="row.itemCode" :readonly="row.isSaved">
                <template #suffix>
                  <el-button size="mini" @click="openProductNameDialog(row)">
                    <i class="el-icon-search"></i>
                  </el-button>
                </template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="物品名称">
            <template #default="{ row }">
              <el-input v-model="row.itemName" :readonly="row.isSaved"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="规格型号">
            <template #default="{ row }">
              <el-input v-model="row.specificationModel" :readonly="row.isSaved"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="单位">
            <template #default="{ row }">
              <el-input v-model="row.unit" :readonly="row.isSaved"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="品牌">
            <template #default="{ row }">
              <el-input v-model="row.brand" :readonly="row.isSaved"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="采购数量">
            <template #default="{ row }">
              <el-input-number v-model.number="row.purchaseQuantity" :min="0" controls-position="right"
                :disabled="row.isSaved"></el-input-number>
            </template>
          </el-table-column>
            <el-table-column label="检验类型">
            <template #default="{ row }">
              <el-select v-model="row.inspectionType" :disabled="row.isSaved" placeholder="请选择检验类型">
                <el-option label="免检" value="免检"></el-option>
                <el-option label="全检" value="全检"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="收货数量">
            <template #default="{ row }">
              <el-input-number 
                v-model.number="row.receivedQuantity" 
                :min="0" 
                :max="row.purchaseQuantity"
                controls-position="right"
                :disabled="!row.isEditing && row.isSaved"
                @change="(val) => validateQuantity(row, '收货数量', val)"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="检验数量">
            <template #default="{ row }">
              <el-input-number 
                v-model.number="row.inspectionQuantity" 
                :min="0" 
                :max="row.purchaseQuantity"
                controls-position="right"
                :disabled="!row.isEditing && row.isSaved"
                @change="(val) => validateQuantity(row, '检验数量', val)"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="合格数量">
            <template #default="{ row }">
              <el-input-number 
                v-model.number="row.qualifiedquantity" 
                :min="0" 
                :max="row.purchaseQuantity"
                controls-position="right"
                :disabled="!row.isEditing && row.isSaved"
                @change="(val) => validateQuantity(row, '合格数量', val)"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="可入库数量">
            <template #default="{ row }">
              <el-input-number 
                v-model.number="row.inboundQuantity" 
                :min="0" 
                :max="row.purchaseQuantity"
                controls-position="right"
                :disabled="!row.isEditing && row.isSaved"
                @change="(val) => validateQuantity(row, '可入库数量', val)"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="退货数量">
            <template #default="{ row }">
              <el-input-number 
                v-model.number="row.returnQuantity" 
                :min="0" 
                :max="row.purchaseQuantity"
                controls-position="right"
                :disabled="!row.isEditing && row.isSaved"
                @change="(val) => validateQuantity(row, '退货数量', val)"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="备注">
            <template #default="{ row }">
              <el-input v-model="row.remarks" :readonly="row.isSaved" type="textarea"></el-input>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="180px">
            <template #default="{ row }">
              <el-button 
                size="small" 
                type="primary" 
                @click="handleEdit(row)" 
                v-if="!row.isEditing && row.isSaved"
              >
                修改
              </el-button>
              <el-button 
                size="small" 
                type="success" 
                @click="handleSaveEdit(row)" 
                v-if="row.isEditing"
              >
                保存
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="handleDelete(row)" 
                :disabled="row.isEditing"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div id="app">
    <el-card>
      <template #header>
        <div class="flex justify-between items-center">
          <span>MinIO 文件上传</span>
        </div>
      </template>
      <el-form ref="formRef1" :model="formData1" label-width="100px">
         <el-form-item label="选择文件">
          <el-upload ref="uploadRef" action="https://localhost:7269/api/FileUpload/UploadFile" :headers="headers"
            :on-success="handleSuccess" :on-error="handleError" :show-file-list="false" :http-request="customRequest">
            <el-button type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">上传文件</el-button>
        </el-form-item>
      </el-form>
      <el-alert v-if="message" :message="message" :type="messageType" :closable="false" style="margin-top: 20px" />
    </el-card>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="key" label="文件名称" width="200" />
      <el-table-column prop="lastModified" label="创建时间" width="200">
        <template #default="scope">
          {{ new Date(scope.row.lastModified).toLocaleString() }}
        </template>
      </el-table-column>
      <el-table-column prop="size" label="文件大小" min-width="200" />
      <el-table-column fixed="right" label="操作" min-width="200">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="openDeleteDialog(scope.row.key)">
            删除文件
          </el-button>
          <el-button link type="primary" size="small" @click="download(scope.row.key)">下载文件</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="isDeleteDialogVisible" title="删除确认" @close="closeDeleteDialog">
      <p>确定要删除该文件吗？</p>
      <template #footer>
        <el-button @click="closeDeleteDialog">取消</el-button>
        <el-button type="primary" @click="confirmDelete">确定</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="isDownloadDialogVisible" title="文件下载">
      <template #content>
        <el-progress :percentage="downloadProgress" :status="downloadStatus"></el-progress>
      </template>
      <template #footer>
        <el-button @click="closeDownloadDialog">关闭</el-button>
      </template>
    </el-dialog>
  </div>
  
      <!--采购编号选择对话框 -->
      <el-dialog v-model="associatedItemDialogVisible1" width="500px" title="采购编号选择" append-to-body>
        <el-table :data="associatedItems1" highlight-current-row border size="small"
          @current-change="handleAssociatedItemChange1">
          <el-table-column type="index" label="序号" />
          <el-table-column property="purchaseOrderNumber" label="采购单号" />
          <el-table-column property="purchaseDate" label="采购日期" />
          <el-table-column property="supplierName" label="供应商名称" />
          <el-table-column property="contactPerson" label="联系人" />
          <el-table-column property="contactPhone" label="联系电话" />
          <el-table-column property="purchasingPersonnel" label="采购人员" />
          <el-table-column property="purchasingDepartment" label="采购部门" />
          <el-table-column property="contactMethod" label="联系方式" />
          <el-table-column property="relatedProject" label="关联项目" />
          <el-table-column property="isDel" label="删除标准" />
        </el-table>
        <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="associatedItems1.length"
        layout="prev, pager, next"
        @current-change="handlePageChange"
        style="margin-top: 10px; text-align: right;"
      />
        <template #footer>
          <el-button @click="pickAssociatedItem1">确定</el-button>
        </template>
      </el-dialog>
  
      <!-- 物料编号选择对话框 -->
      <el-dialog v-model="productNameDialogVisible" width="500px" title="物料编号选择" append-to-body>
        <el-table :data="productNames" highlight-current-row border size="small"
          @current-change="handleProductNameChange">
          <el-table-column type="index" label="序号" />
          <el-table-column property="itemNumber" label="物料编号" />
          <el-table-column property="itemName" label="物料名称" />
          <el-table-column property="itemspecification" label="物料规格" />
          <el-table-column property="itemType" label="物料类型" />
          <el-table-column property="lotNumber" label="批次号" />
          <el-table-column property="manufactureDate" label="生产日期" />
          <el-table-column property="expirationDate" label="有效期" />
          <el-table-column property="plannedQuantity" label="计划备料数量" />
          <el-table-column property="actualQuantity" label="实际备料数量" />
          <el-table-column property="unit" label="单位" />
          <el-table-column property="packagingPlanId" label="计划主键" />
        </el-table>
        <template #footer>
          <el-button @click="pickProductName">确定</el-button>
        </template>
      </el-dialog>

    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted, watch } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { useRouter, useRoute } from 'vue-router';
  import { Materialread, Materialwrite } from '@/axios/axiosHelper';
  import axios from 'axios';
  import { nextTick } from 'vue';
  
  const formRef = ref(null);
  const currentUser = ref("admin");
  const router = useRouter();
  const route = useRoute();
  
  // 主表单数据
  const formData = reactive({

    "inspectionSubject": "",
    "inspectionOrderNumber": "",
    "inspectionDate": "",
    "inspectionPersonnel":  currentUser.value,
    "department": "",
    "contactInformation": "",
    "purchaseOrderNumber": "",
    "purchaseDate": "",
    "supplierName": "",
    "contactPerson": "",
    "contactPhone": "",
    "purchasingPersonnel": "",
    "purchasingDepartment": "",
    "contactMethod": "",
    "relatedProject": "",
    "remarks": "",
    "isDel": true
  });

  // 主表单验证规则
  const rules = reactive({
    bomSubject: [
      { required: true, message: '不能为空', trigger: 'blur' }
    ],
    productName: [
      { required: true, message: '不能为空', trigger: 'blur' }
    ],
    documentNo: [
      { required: true, message: '不能为空', trigger: 'blur' }
    ],
    contactInformation: [
      { required: true, message: '请输入联系电话', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入11位有效的手机号码', trigger: 'blur' }
    ],
    contactPhone: [
      { required: true, message: '请输入联系电话', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入11位有效的手机号码', trigger: 'blur' }
    ],
    contactMethod: [
      { required: true, message: '请输入联系电话', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入11位有效的手机号码', trigger: 'blur' }
    ]
  });
  
  // 明细数据列表
  const planDetailsList = ref([]);
  const attachments = ref([]);
  
  // 保存主表单和明细
  const saveAll = async () => {
  if (formRef.value) {
      const isValid = await formRef.value.validate();
      if (isValid) {
          try {
              // 验证所有数量
              const hasInvalidQuantity = planDetailsList.value.some(row => {
                  return row.receivedQuantity > row.purchaseQuantity ||
                         row.inspectionQuantity > row.purchaseQuantity ||
                         row.qualifiedquantity > row.purchaseQuantity ||
                         row.inboundQuantity > row.purchaseQuantity ||
                         row.returnQuantity > row.purchaseQuantity;
              });

              if (hasInvalidQuantity) {
                  ElMessage.error('存在超过采购数量的记录，请检查后重试');
                  return;
              }

              // 保存主表单
              const response = await Materialwrite.post('f-write/api/Arrival/AddBasicInfo', formData);
              if (response.data.code === 200) {
                  formData.basicInfoid = response.data.data.basicInfoid;
                  console.log('表主键', formData.basicInfoid);
                  ElMessage.success('主表单保存成功');

                  // 更新明细表的外键并保存
                  const saveDetailPromises = planDetailsList.value.map(async (row) => {
                      if (!row.isSaved) {  // 只保存未保存的记录
                          const detailData = {
                              ...row,
                              basicInfoid: formData.basicInfoid
                          };
                          
                          const detailResponse = await Materialwrite.post(
                              '/f-write/api/Arrival/AddPurchaseInfo',
                              detailData
                          );
                          
                          if (detailResponse.data.code === 200) {
                              row.isSaved = true;
                              row.PurchaseInfoid = detailResponse.data.data.purchaseInfoid;  // 保存返回的ID
                              return true;
                          } else {
                              ElMessage.error(`明细保存失败：${detailResponse.data.message}`);
                              return false;
                          }
                      }
                      return true;
                  });

                  const results = await Promise.all(saveDetailPromises);
                  if (results.every(result => result)) {
                      ElMessage.success('所有明细保存成功');
                      router.push("/GetArrival");
                  }
              } else {
                  ElMessage.error(`主表单保存失败：${response.data.message}`);
              }
          } catch (error) {
              console.error('保存过程中发生错误:', error.response?.data);
              ElMessage.error('保存过程中发生错误，请检查网络或联系管理员');
          }
      }
  }
};
  
  
  // 新增行
  const addNewRow = () => {
    planDetailsList.value.push({
      "itemCode": "",
      "itemName": "",
      "specificationModel": "",
      "unit": "",
      "brand": "",
      "purchaseQuantity": 0,
      "inspectionType": "",
      "receivedQuantity": 0,
      "inspectionQuantity": 0,
      "qualifiedquantity": 0,
      "inboundQuantity": 0,
      "returnQuantity": 0,
      "remarks": "",
      "basicInfoid": 0,
      "isDel": true,
      "isEditing": false,  // 添加编辑状态控制
      "isSaved": false     // 添加保存状态控制
    });
  };
  
  // 删除单条记录
  const DeleteProductionPlanning = async (purchaseInfoid) => {
    try {
      const confirmResult = await ElMessageBox.confirm(
        '确认删除该条记录？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      );
      if (confirmResult === 'confirm') {
        const response = await Materialwrite.post(
          `f-write/api/Arrival/DelPurchaseInfo`,
          { purchaseInfoid: purchaseInfoid.toString() }, // 修改这里，将参数放在请求体中
          {
            params: {PurchaseInfoid: purchaseInfoid.toString()} // 这里保持为空，因为参数已经在请求体中
          }
        );
        if (response.data.code === 200) {
          ElMessage.success('删除成功');
          ShowMaterials(); // 调用 ShowMaterials 方法刷新数据
        } else {
          ElMessage.error(`删除失败：${response.data.message}`);
        }
      }
    } catch (error) {
       
    }
  };
  // 物料编号数据
  const productNames = ref([]);
  
  const productNameDialogVisible = ref(false);
  const currentProductNameRow = ref(null);
  const currentProductName = ref({});
  
  // 获取物料信息
  const fetchProducts = () => {
    Materialread.get("p2-read/api/MaterialPreparation/Handle?TotalIndex=1&TotalPage=23")
      .then(res => {
        productNames.value = res.data.data;
        console.log("产品数据：", productNames.value);
        nextTick(() => {
          // 强制更新表格
        });
      })
  };
  
  
  
  // 打开物料编号选择对话框
  const openProductNameDialog = (row) => {
    if (productNames.value.length === 0) {
      ElMessage.warning('产品信息正在加载，请稍后重试');
      return;
    }
    currentProductNameRow.value = row;
    productNameDialogVisible.value = true;
  };
  
  // 当前选中的物料编号行
  const handleProductNameChange = (val) => {
    currentProductName.value = val;
  };
  
  // 选择物料编号
  const pickProductName = () => {
    if (currentProductName.value && currentProductNameRow.value) {
      currentProductNameRow.value.itemCode = currentProductName.value.lotNumber;//物料编号
      currentProductNameRow.value.itemName = currentProductName.value.itemName;//物料名称
      currentProductNameRow.value.specificationModel = currentProductName.value.itemspecification;//规格
      currentProductNameRow.value.unit = currentProductName.value.unit;//单位
      currentProductNameRow.value.brand = currentProductName.value.itemType;//类型
      currentProductNameRow.value.purchaseQuantity = currentProductName.value.plannedQuantity;//库存数量
      currentProductNameRow.value.productInfoFilled = true; // 设置标志位，表示产品信息已填充
      productNameDialogVisible.value = false;
    }
  };
  onMounted(() => {
    fetchAssociatedProjects1();
    fetchProducts();
  
  });
  
  // 对话框显示状态
  const associatedItemDialogVisible1 = ref(false);
  const currentAssociatedItem1 = ref({});
  // 关联项目数据
  const associatedItems1 = ref([]);
  // 打开关联项目选择对话框
  const openAssociatedItemDialog1 = () => {
    associatedItemDialogVisible1.value = true;
  };
  // 当前选中的关联项目行
  const handleAssociatedItemChange1 = (val) => {
    currentAssociatedItem1.value = val;
  };
  // 选择关联项目
  const pickAssociatedItem1 = () => {
    if (currentAssociatedItem1.value) {
      formData.purchaseOrderNumber = currentAssociatedItem1.value.purchaseOrderNumber; // 采购单号
      formData.purchaseDate = currentAssociatedItem1.value.purchaseDate; // 采购日期
      formData.supplierName = currentAssociatedItem1.value.supplierName; // 供应商名称
      formData.contactPerson = currentAssociatedItem1.value.contactPerson; // 联系人
      formData.contactPhone = currentAssociatedItem1.value.contactPhone; // 联系电话
      formData.purchasingPersonnel = currentAssociatedItem1.value.purchasingPersonnel; // 采购人员
      formData.purchasingDepartment = currentAssociatedItem1.value.purchasingDepartment; // 采购部门
      formData.contactMethod = currentAssociatedItem1.value.contactMethod; //联系方式
      formData.relatedProject = currentAssociatedItem1.value.relatedProject; // 关联项目
      associatedItemDialogVisible1.value = false;
    }
  };
  // 获取关联项目数据
  const fetchAssociatedProjects1 = () => {
    Materialread.get("f-read/api/Arrival/GetPurchaseOrder")
      .then(res => {
        associatedItems1.value = res.data.data;
  
      })
    // .catch(error => {
    //   console.error('获取产品信息失败:', error);
    //   ElMessage.error('获取产品信息失败，请检查网络或联系管理员');
    // });
  };
  

  
const formRef1 = ref(null);
const uploadRef = ref(null);
const formData1 = ref({});
const message = ref('');
const messageType = ref('');
const tableData = ref([{
  key: "",
  lastModified: "",
  eTag: "",
  size: 0,
  isDir: false,
  versionId: null,
  contentType: null,
  expires: null,
  userMetadata: null,
  isLatest: false,
  lastModifiedDateTime: "",
}]);
const isDeleteDialogVisible = ref(false);
const currentDeleteKey = ref('');
const isDownloadDialogVisible = ref(false);
const downloadProgress = ref(0);
const downloadStatus = ref('');

onMounted(() => {
  listObjects();
});

const download = async (key) => {
  isDownloadDialogVisible.value = true;
  downloadProgress.value = 0;
  downloadStatus.value = 'active';
  try {
    const response = await axios.get(`/api/FileUpload/DownloadFile?objectName=${key}`, {
      responseType: 'blob',
      onDownloadProgress: (progressEvent) => {
        const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        downloadProgress.value = percentCompleted;
      }
    });
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', key);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    downloadStatus.value = 'success';
  } catch (error) {
    console.error('文件下载失败:', error);
    message.value = '文件下载失败: ' + (error.response?.data?.error || error.message);
    messageType.value = 'error';
    downloadStatus.value = 'exception';
  }
};

const listObjects = async () => {
  axios.get("https://localhost:7212/api/FileUpload/ListObjectsInOneBucket")
    .then((res) => {
      tableData.value = res.data;
      console.log("查询成功", res.data);
    })
    .catch((err) => {
      console.log(err);
    });
};

const headers = {
  'Content-Type': 'multipart/form-data'
};

const customRequest = async (options) => {
  const formData = new FormData();
  formData.append('file', options.file);
  const response = await axios.post(options.action, formData, {
    headers: headers
  });
  options.onSuccess(response.data);
  if (response.data != null) {
    alert("添加成功");
    return;
  } else {
    alert("添加失败");
    return;
  }
};

const handleError = (error) => {
  message.value = '上传失败: ' + (error.response?.data?.error || error.message);
  messageType.value = 'error';
};

const submitForm = () => {
  uploadRef.value.submit();
};

const openDeleteDialog = (key) => {
  currentDeleteKey.value = key;
  isDeleteDialogVisible.value = true;
};

const closeDeleteDialog = () => {
  isDeleteDialogVisible.value = false;
  currentDeleteKey.value = '';
};

const confirmDelete = () => {
  axios.delete("https://localhost:7212/api/FileUpload/DeleteObjectInOneBucket", {
    params: {
      objectName: currentDeleteKey.value
    }
  })
    .then((res) => {
      console.log("删除成功", res.data);
      message.value = '文件删除成功';
      messageType.value = 'success';
      listObjects();
      closeDeleteDialog();
    })
    .catch((err) => {
      console.log(err);
      message.value = '文件删除失败: ' + (err.response?.data?.error || err.message);
      messageType.value = 'error';
      closeDeleteDialog();
    });
};

const closeDownloadDialog = () => {
  isDownloadDialogVisible.value = false;
  downloadProgress.value = 0;
  downloadStatus.value = '';
};


const handleEdit = (row) => {
  row.isEditing = true;
  // 保存原始数据，用于取消编辑时恢复
  row._originalData = { ...row };
};

const handleSaveEdit = async (row) => {
  try {
    const response = await axios.post(
      'https://localhost:7229/api/Arrival/UpdatePurchaseInfo',
      row
    );
    if (response.data.code === 200) {
      ElMessage.success('修改成功');
      row.isEditing = false;
      delete row._originalData;
    } else {
      ElMessage.error(`修改失败：${response.data.message}`);
    }
  } catch (error) {
    console.error('修改过程中发生错误:', error);
    ElMessage.error('修改过程中发生错误，请检查网络或联系管理员');
  }
};

// 修改删除方法
const handleDelete = async (row) => {
  try {
    // 如果是已保存的记录，需要调用后端删除
    if (row.isSaved && row.PurchaseInfoid) {
      const confirmResult = await ElMessageBox.confirm(
        '确认删除该条记录？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      );
      
      if (confirmResult === 'confirm') {
        const response = await axios.post(
          'https://localhost:7229/api/Arrival/DelPurchaseInfo',
          { purchaseInfoid: row.PurchaseInfoid.toString() }
        );
        
        if (response.data.code === 200) {
          ElMessage.success('删除成功');
          // 从列表中移除该行
          const index = planDetailsList.value.findIndex(item => item.PurchaseInfoid === row.PurchaseInfoid);
          if (index !== -1) {
            planDetailsList.value.splice(index, 1);
          }
        } else {
          ElMessage.error(`删除失败：${response.data.message}`);
        }
      }
    } else {
      // 如果是未保存的记录，直接从列表中移除
      const index = planDetailsList.value.indexOf(row);
      if (index !== -1) {
        planDetailsList.value.splice(index, 1);
        ElMessage.success('删除成功');
      }
    }
  } catch (error) {
    console.error('删除过程中发生错误:', error);
    ElMessage.error('删除过程中发生错误，请检查网络或联系管理员');
  }
};

const validateQuantity = (row, field, value) => {
  if (value > row.purchaseQuantity) {
    ElMessage.warning(`${field}不能超过采购数量`);
    row[field] = row.purchaseQuantity;
    return false;
  }
  return true;
};

// 添加 watch 函数来监听数量变化
watch(() => planDetailsList.value, (newList) => {
  newList.forEach(row => {
    // 监听收货数量
    watch(() => row.receivedQuantity, (newVal) => {
      if (newVal > row.purchaseQuantity) {
        validateQuantity(row, '收货数量', newVal);
      }
    });

    // 监听检验数量
    watch(() => row.inspectionQuantity, (newVal) => {
      if (newVal > row.purchaseQuantity) {
        validateQuantity(row, '检验数量', newVal);
      }
    });

    // 监听合格数量
    watch(() => row.qualifiedquantity, (newVal) => {
      if (newVal > row.purchaseQuantity) {
        validateQuantity(row, '合格数量', newVal);
      }
    });

    // 监听可入库数量
    watch(() => row.inboundQuantity, (newVal) => {
      if (newVal > row.purchaseQuantity) {
        validateQuantity(row, '可入库数量', newVal);
      }
    });

    // 监听退货数量
    watch(() => row.returnQuantity, (newVal) => {
      if (newVal > row.purchaseQuantity) {
        validateQuantity(row, '退货数量', newVal);
      }
    });
  });
}, { deep: true });
 
 

  </script>
  
  <style scoped>
  .production-plan {
    padding: 20px;
  }
  
  .title {
    text-align: center;
    margin-bottom: 20px;
  }
  
  .sub-title {
    margin: 20px 0 10px;
    font-size: 16px;
    font-weight: 500;
  }
  
  .detail-section,
  .attachment-section {
    margin-top: 20px;
  }
  
  .el-table {
    margin-top: 10px;
  }
  </style>